import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router } from '@angular/router';
import {
  CellActionDescriptor,
  DateEntityTableColumn,
  EntityTableColumn,
  EntityTableConfig,
  GroupActionDescriptor,
  HeaderActionDescriptor
} from '@home/models/entity/entities-table-config.models';
import { TranslateService } from '@ngx-translate/core';
import { DatePipe } from '@angular/common';
import { EntityType, entityTypeResources, entityTypeTranslations } from '@shared/models/entity-type.models';
import { Observable, of } from 'rxjs';
import { select, Store } from '@ngrx/store';
import { selectAuthUser } from '@core/auth/auth.selectors';
import { map, mergeMap, take, tap } from 'rxjs/operators';
import { AppState } from '@core/core.state';
import { Authority } from '@app/shared/models/authority.enum';
import { CustomerService } from '@core/http/customer.service';
import { Customer } from '@app/shared/models/customer.model';
import { BroadcastService } from '@core/services/broadcast.service';
import { MatDialog } from '@angular/material/dialog';
import { DialogService } from '@core/services/dialog.service';

import {
  AddEntitiesToCustomerDialogComponent,
  AddEntitiesToCustomerDialogData
} from './dialog/add-entities-to-customer-dialog/add-entities-to-customer-dialog.component';
import { VideoInfo } from '@app/shared/models/video.models';
import { VideoService } from '@app/core/http/video.service';
import { VideoComponent } from './video.component';
import { VideoId } from '@app/shared/models/id/video-id';
import { VideoTabsComponent } from './video-tabs.component';
import { HomeDialogsService } from '@home/dialogs/home-dialogs.service';
import {  SingleVideoPlayComponent } from './dialog/single-video-play/single-video-play.component';
import { VideoImportComponent } from './dialog/video-import/video-import.component';
import { VideosPlayComponent } from './dialog/videos-play/videos-play.component';

@Injectable()
export class VideoTableConfigResolver implements Resolve<EntityTableConfig<VideoInfo>> {

  private readonly config: EntityTableConfig<VideoInfo> = new EntityTableConfig<VideoInfo>();

  private customerId: string;


  constructor(private store: Store<AppState>,
              private broadcast: BroadcastService,
              private VideoService: VideoService,
              private customerService: CustomerService,
              private dialogService: DialogService,
              private homeDialogs: HomeDialogsService,
              private translate: TranslateService,
              private datePipe: DatePipe,
              private router: Router,
              private dialog: MatDialog) {
                ;
    this.config.entityType = EntityType.VIDEO;
    this.config.entityComponent = VideoComponent;
    this.config.entityTabsComponent = VideoTabsComponent;
    this.config.entityTranslations = entityTypeTranslations.get(EntityType.VIDEO);
    this.config.entityResources = entityTypeResources.get(EntityType.VIDEO);

    this.config.deleteEntityTitle = Video => this.translate.instant('video.delete-video-title', { VideoName: Video.name });
    this.config.deleteEntityContent = () => this.translate.instant('video.delete-video-text');
    this.config.deleteEntitiesTitle = count => this.translate.instant('video.delete-videos-title', {count});
    this.config.deleteEntitiesContent = () => this.translate.instant('video.delete-videos-text');

    this.config.loadEntity = id => { let i = id as unknown as string ;return this.VideoService.getVideoInfo(i);}
    this.config.saveEntity = Video => {
      return this.VideoService.saveVideo(Video).pipe(
        tap(() => {
          this.broadcast.broadcast('VideoSaved');
        }),
        mergeMap((savedVideo) => { 
          return  this.VideoService.getVideoInfo(savedVideo)}
        ));
    };
    //this.config.onEntityAction = action => this.onVideoAction(action);
    this.config.detailsReadonly = () => this.config.componentsData.VideoScope === 'customer_user';

 //   this.config.headerComponent = VideoTableHeaderComponent;
// this.entitiesTableConfig.entityTranslations;
// this.entityTranslations={};


  }

  playVideo($event, entity){
    console.log($event,entity)

    if ($event) {
      $event.stopPropagation();
    }


    this.dialog.open<SingleVideoPlayComponent>(SingleVideoPlayComponent, {
      disableClose: true,
      panelClass: ['tb-dialog', 'tb-fullscreen-dialog'],
      data: {
        cameraId: entity.cameraId,
        entityType: EntityType.VIDEO
      }
    }).afterClosed()
      .subscribe((res) => {
        if (res) {
          this.config.updateData();
        }
      });


  }
  resolve(route: ActivatedRouteSnapshot): Observable<EntityTableConfig<VideoInfo>> {
    ;
    const routeParams = route.params;
    this.config.componentsData = {
      VideoScope: route.data.VideosType,
      VideoType: ''
    };
    this.customerId = routeParams.customerId;
    return this.store.pipe(select(selectAuthUser), take(1)).pipe(
      tap((authUser) => {
        if (authUser.authority === Authority.CUSTOMER_USER) {
          this.config.componentsData.VideoScope = 'customer_user';
          this.customerId = authUser.customerId;
        }
      }),
      mergeMap(() =>
        this.customerId ? this.customerService.getCustomer(this.customerId) : of(null as Customer)
      ),
      map((parentCustomer) => {
        if (parentCustomer) {
          if (parentCustomer.additionalInfo && parentCustomer.additionalInfo.isPublic) {
            this.config.tableTitle = this.translate.instant('customer.public-Videos');
          } else {
            this.config.tableTitle = parentCustomer.title + ': ' + this.translate.instant('video.cam-name');
          }
        } else {
          this.config.tableTitle = this.translate.instant('video.config');
        }
        this.config.columns = this.configureColumns(this.config.componentsData.VideoScope);
        this.configureEntityFunctions(this.config.componentsData.VideoScope);
        this.config.cellActionDescriptors = this.configureCellActions(this.config.componentsData.VideoScope);
        this.config.groupActionDescriptors = this.configureGroupActions(this.config.componentsData.assetScope);
        this.config.addActionDescriptors = this.configureAddActions(this.config.componentsData.VideoScope);
        this.config.addEnabled = this.config.componentsData.VideoScope !== 'customer_user';
        this.config.entitiesDeleteEnabled =true;
        this.config.deleteEnabled = () => true;
        this.config.headerActionDescriptors= this.addHeaderActionDescriptors(this.config.componentsData.VideoScope);
       // this.config.entitySelectionEnabled=(i)=> {console.log(i);return false};
        return this.config;
      })
    );
  }

  configureColumns(VideoScope: string): Array<EntityTableColumn<VideoInfo>> {
    ;
    const columns: Array<EntityTableColumn<VideoInfo>> = [
      new EntityTableColumn<VideoInfo>('orgName', 'video.org-name', '20%'),
      new EntityTableColumn<VideoInfo>('orgCode', 'video.org-code', '20%'),
      new EntityTableColumn<VideoInfo>('name', 'video.name', '20%'),
      new EntityTableColumn<VideoInfo>('ip', 'video.ip', '20%'),
      new EntityTableColumn<VideoInfo>('cameraId', 'video.camera-id', '20%'),
    ];
    return columns;
  }
  configureEntityFunctions(VideoScope: string): void {


    this.config.entitiesFetchFunction = pageLink =>{

      return        this.VideoService.getVideoInfos(this.customerId, pageLink, this.config.componentsData.VideoType)
      ;}
    this.config.deleteEntity = (id) =>{ let i=((id as unknown) as string) ; return  this.VideoService.deleteVideo(i)};
  }
  configureGroupActions(assetScope: string): Array<GroupActionDescriptor<VideoInfo>> {
    const actions: Array<GroupActionDescriptor<VideoInfo>> = [];

      actions.push(
        {
          name: this.translate.instant('video.play-videos'),
          icon: 'play_circle_outline',
          isEnabled: true,
          onAction: ($event, entities) => this.VideosPlay($event, entities.map((entity) => entity.id))
        }
      );


    return actions;
  }
  configureCellActions(VideoScope: string): Array<CellActionDescriptor<VideoInfo>> {
    const actions: Array<CellActionDescriptor<VideoInfo>> = [];
    actions.push(
      {
        name: this.translate.instant('video.play-video'),
        icon: 'play_circle_filled',
        isEnabled: (entity) => true,
        onAction: ($event, entity) =>{ this.playVideo($event, entity);return ;}
      })

    return actions;
  }


  addHeaderActionDescriptors(VideoScope: string): Array<HeaderActionDescriptor> {
    const actions: Array<HeaderActionDescriptor> = [];

      actions.push(
        {
          name: this.translate.instant('video.import-camera'),
          icon: 'local_see',
          isEnabled: () => true,
          onAction: ($event) => {
            if ($event) {
              $event.stopPropagation();
            }
            ;
            this.dialog.open<VideoImportComponent>(VideoImportComponent, {
              disableClose: true,
              panelClass: ['tb-dialog', 'tb-fullscreen-dialog'],
              data: {
                customerId: this.customerId,
                entityType: EntityType.VIDEO
              }
            }).afterClosed()
              .subscribe((res) => {
                  this.config.updateData();
              });

          }
        },
      )

    return actions;
  }
  configureAddActions(VideoScope: string): Array<HeaderActionDescriptor> {
    const actions: Array<HeaderActionDescriptor> = []; 
      actions.push(
        {
          name: this.translate.instant('video.add-video-text'),
          icon: 'add',
          isEnabled: () => true,
          // onAction: ($event) => this.config.addEntity()
          onAction: ($event) => this.config.getTable().addEntity($event)
        },
      )
    return actions;
  }

  importVideos($event: Event) {
    this.homeDialogs.importEntities(EntityType.VIDEO).subscribe((res) => {
      if (res) {
        this.broadcast.broadcast('VideoSaved');
        this.config.updateData();
      }
    });
  }

  addVideosToCustomer($event: Event) {
    if ($event) {
      $event.stopPropagation();
    }
    ;
    this.dialog.open<AddEntitiesToCustomerDialogComponent, AddEntitiesToCustomerDialogData,
      boolean>(AddEntitiesToCustomerDialogComponent, {
      disableClose: true,
      panelClass: ['tb-dialog', 'tb-fullscreen-dialog'],
      data: {
        customerId: this.customerId,
        entityType: EntityType.VIDEO
      }
    }).afterClosed()
      .subscribe((res) => {
        if (res) {
          this.config.updateData();
        }
      });
  }

  VideosPlay($event: Event, VideoIds: Array<VideoId>) {
    if ($event) {
      $event.stopPropagation();
    }
    this.dialog.open<VideosPlayComponent>(VideosPlayComponent, {
      disableClose: true,
      panelClass: ['tb-dialog', 'tb-fullscreen-dialog'],
      data: {
        vids: VideoIds,
        entityType: EntityType.VIDEO
      }
    }).afterClosed()
      .subscribe((res) => {
        if (res) {
          this.config.updateData();
        }
      });
  }

}
